﻿using M56.Core.Utils;
using Newtonsoft.Json;

namespace BarrageGameAssistant.Core.Model.Base
{
    /// <summary>
    /// 项目配置基类
    /// </summary>
    public abstract class ConfigBase
    {
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="path"></param>
        public virtual void Save(string path)
        {
            var jsonStr = JsonUtils.ToJson(this, JsonUtils.DefaultSetting(true));
            File.WriteAllText(path, jsonStr);
        }

        /// <summary>
        /// 载入配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="jsonConverters"></param>
        /// <returns></returns>
        protected static T? Load<T>(string path, List<JsonConverter>? jsonConverters = null) where T : ConfigBase
        {
            try
            {
                T? project;
                var jsonStr = File.ReadAllText(path);

                if (jsonConverters != null)
                    project = JsonUtils.FromJson<T>(jsonStr, true, [.. jsonConverters]);
                else
                    project = JsonUtils.FromJson<T>(jsonStr, true);

                if (project == null)
                {
                    project = default;
                    project?.Save(path);
                }
                return project;

            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
